package com.srcbox.file.util

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.provider.Settings
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieCompositionFactory
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.srcbox.file.R
import com.srcbox.file.data.AppSetting
import kotlinx.android.synthetic.main.main_one_list_adapter.view.*
import java.text.DecimalFormat


class NotificationDialog(private val context: Activity, private val type: Int) {
    private var dialog: AlertDialog? = null
    private var content: String? = null
    fun ball(content: String, updateUrl: String = "", appVersion: Float): AlertDialog? {
        this.content = content
        dialog = AlertDialog.Builder(context).create()
        dialog?.setCanceledOnTouchOutside(false)
        dialog?.show()
        val dialogWin = dialog?.window
        dialogWin?.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        dialogWin?.setContentView(R.layout.notification_dialog)
        val diaContent = dialogWin?.findViewById<TextView>(R.id.dia_content)
        val diaClose = dialogWin?.findViewById<TextView>(R.id.dia_close)
        val diaOK = dialogWin?.findViewById<TextView>(R.id.dia_ok)
        diaContent?.text = content

        /*diaContent?.setOnClickListener {
            EggUtil.copyText(context, it.text.toString())
            EggUtil.toast(context, "已复制")
        }*/

        diaClose?.setOnClickListener {
            dialog?.cancel()
        }

        when (type) {
            DAY_CONTENT -> {
                dialog?.setCanceledOnTouchOutside(true)
                diaOK?.visibility = View.GONE
            }
            APP_UPDATE -> {
                diaOK?.text = "更新"
                diaOK?.setOnClickListener {
                    diaOK.text = "准备中..."
                    FileDownloader.setup(context)
                    val fileName = "updateApp$appVersion.apk"
                    val downPath = "${context.filesDir}/apk/$fileName"
                    FileDownloader.getImpl().create(updateUrl)
                        .setPath(downPath)
                        .setListener(object : FileDownloadListener() {
                            override fun pending(
                                task: BaseDownloadTask,
                                soFarBytes: Int,
                                totalBytes: Int
                            ) {
                                println("a")
                                diaOK.text = "等待中..."
                            }

                            override fun connected(
                                task: BaseDownloadTask,
                                etag: String,
                                isContinue: Boolean,
                                soFarBytes: Int,
                                totalBytes: Int
                            ) {
                                diaOK.text = "启动中..."
                            }

                            override fun progress(
                                task: BaseDownloadTask,
                                soFarBytes: Int,
                                totalBytes: Int
                            ) {
                                val pro = soFarBytes.toFloat() / totalBytes.toFloat()
                                diaOK.text = DecimalFormat(".00").format((pro * 100.0))
                                println("c$soFarBytes")
                            }

                            override fun blockComplete(task: BaseDownloadTask) {}
                            override fun retry(
                                task: BaseDownloadTask,
                                ex: Throwable,
                                retryingTimes: Int,
                                soFarBytes: Int
                            ) {
                                println("d")
                            }

                            override fun completed(task: BaseDownloadTask) {
                                diaOK.text = "点击安装"
                                if (Build.VERSION.SDK_INT >= 26) {
                                    if (!context.packageManager.canRequestPackageInstalls()) {
                                        EggUtil.toast(context, "请授权")
                                        EggUtil.startInstallPermissionSettingActivity(context)
                                        return
                                    }
                                }
                                EggUtil.startInstall(context, fileName)
                            }

                            override fun paused(
                                task: BaseDownloadTask,
                                soFarBytes: Int,
                                totalBytes: Int
                            ) {
                                println("e")
                            }

                            override fun error(
                                task: BaseDownloadTask,
                                e: Throwable
                            ) {
                                EggUtil.toast(context, "出现错误：$e")
                            }

                            override fun warn(task: BaseDownloadTask) {}
                        }).start()


                }
            }
        }
        return dialog
    }


    companion object {
        const val DAY_CONTENT = 1
        const val APP_UPDATE = 2
    }


    fun makeLayout(): View {
        val lin = LinearLayout(context)
        val linParams = WindowManager.LayoutParams()
        linParams.width = -1
        linParams.height = 200
        lin.setBackgroundColor(Color.parseColor("#ffffff"))
        lin.layoutParams = linParams
        lin.orientation = LinearLayout.VERTICAL
        val lottieAnnotation = LottieAnimationView(context)
        val lottieCompositionFactory =
            LottieCompositionFactory.fromAsset(context, "anim/update.json")
        lottieCompositionFactory.addListener {
            lottieAnnotation.setComposition(it)
            lottieAnnotation.repeatCount = -1
            lottieAnnotation.playAnimation()
        }
        lin.addView(lottieAnnotation)

        val textV = TextView(context)
        textV.text = content
        val textParams = LinearLayout.LayoutParams(-2, -2)
        val margin = EggUtil.dp2px(context, 15f)
        textParams.setMargins(margin, margin, margin, margin)
        textV.layoutParams = textParams
        lin.addView(textV)

        val lin2 = LinearLayout(context)
        val lin2Params = WindowManager.LayoutParams()
        lin2Params.width = -1
        lin2Params.height = EggUtil.dp2px(context, 40f)
        lin2.layoutParams = lin2Params
        lin2.orientation = LinearLayout.HORIZONTAL

        val startTextV = TextView(context)
        val closeTextV = TextView(context)
        startTextV.text = "确定"
        closeTextV.text = "关闭"


        val buttonTextParams = WindowManager.LayoutParams()
        buttonTextParams.width = -1
        buttonTextParams.height = -1
        buttonTextParams.horizontalWeight = 1f
        startTextV.layoutParams = buttonTextParams
        closeTextV.layoutParams = buttonTextParams
        lin2.addView(startTextV)
        lin2.addView(closeTextV)
        lin.addView(lin2)
        return lin
    }
}